package com.wb.base.refreshview;


import android.content.Context;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.AttributeSet;

public class LoadMoreRecyclerView extends RecyclerView implements ILoad {

    public static class WrapContentLinearLayoutManager extends LinearLayoutManager {
        public WrapContentLinearLayoutManager(Context context) {
            super(context);
        }

        public WrapContentLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
            super(context, orientation, reverseLayout);
        }

        public WrapContentLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
        }

        @Override
        public void onLayoutChildren(Recycler recycler, State state) {
            try {
                super.onLayoutChildren(recycler, state);
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        }
    }

    private OnScrollListener mOnScrollListener;

    protected LAYOUT_MANAGER_TYPE layoutManagerType;
    private boolean isLoadingMore = false;//用于
    private boolean mIsLoadMoreWidgetEnabled = false;//是否启用刷新

    private OnLoadMoreListener onLoadMoreListener;

    private int lastVisibleItemPosition;
    private int mFirstVisibleItem;
    private int mVisibleItemCount = 0;
    private int mTotalItemCount = 0;
    private int previousTotal = 0;

    private LoadRecyclerViewAdapter mAdapter;


    public void setAdapter(LoadRecyclerViewAdapter adapter) {
        super.setAdapter(adapter);
        this.mAdapter = adapter;
    }


    public static enum LAYOUT_MANAGER_TYPE {
        LINEAR,
        GRID,
        STAGGERED_GRID
    }


    @Override
    public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
        this.onLoadMoreListener = onLoadMoreListener;
    }

    public LoadMoreRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setLayoutManager(new WrapContentLinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
    }

    private int findMax(int[] lastPositions) {
        int max = Integer.MIN_VALUE;
        for (int value : lastPositions) {
            if (value > max)
                max = value;
        }
        return max;
    }

    private int findMin(int[] lastPositions) {
        int min = Integer.MAX_VALUE;
        for (int value : lastPositions) {
            if (value != RecyclerView.NO_POSITION && value < min)
                min = value;
        }
        return min;
    }


    /**
     * 启用加载更多
     */
    @Override
    public void enableLoadmore() {

        if (mOnScrollListener == null) {
            removeOnScrollListener(mOnScrollListener);
            mOnScrollListener = new OnScrollListener() {
                private int[] lastPositions;

                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);

                    if (!mIsLoadMoreWidgetEnabled) {
                        return;
                    }

                    LayoutManager layoutManager = recyclerView.getLayoutManager();

                    if (layoutManagerType == null) {
                        if (layoutManager instanceof GridLayoutManager) {
                            layoutManagerType = LAYOUT_MANAGER_TYPE.GRID;
                        } else if (layoutManager instanceof LinearLayoutManager) {
                            layoutManagerType = LAYOUT_MANAGER_TYPE.LINEAR;
                        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
                            layoutManagerType = LAYOUT_MANAGER_TYPE.STAGGERED_GRID;
                        } else {
                            throw new RuntimeException("Unsupported LayoutManager used. Valid ones are LinearLayoutManager, GridLayoutManager and StaggeredGridLayoutManager");
                        }
                    }

                    switch (layoutManagerType) {
                        case LINEAR:
                            mVisibleItemCount = layoutManager.getChildCount();
                            mTotalItemCount = layoutManager.getItemCount();
                        case GRID:
                            lastVisibleItemPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
                            mFirstVisibleItem = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();
                            break;
                        case STAGGERED_GRID:
                            StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager;
                            if (lastPositions == null)
                                lastPositions = new int[staggeredGridLayoutManager.getSpanCount()];

                            staggeredGridLayoutManager.findLastVisibleItemPositions(lastPositions);
                            lastVisibleItemPosition = findMax(lastPositions);

                            staggeredGridLayoutManager.findFirstVisibleItemPositions(lastPositions);
                            mFirstVisibleItem = findMin(lastPositions);
                            break;
                    }

//                if (isLoadingMore) {
//                    //todo: there are some bugs needs to be adjusted for admob adapter
//                    if (mTotalItemCount > previousTotal) {
//                        isLoadingMore = false;
                    previousTotal = mTotalItemCount;
//                    }
//                }

                    if (!isLoadingMore && (mTotalItemCount - mVisibleItemCount) <= mFirstVisibleItem) {
                        //todo: there are some bugs needs to be adjusted for admob adapter

                        if (mAdapter.getItemCount() > 0) {
                            if (onLoadMoreListener != null) {
                                onLoadMoreListener.loadMore(mAdapter.getItemCount(), lastVisibleItemPosition);
                                isLoadingMore = true;
                            }
                        }
                        previousTotal = mTotalItemCount;
                    }
                }

            };
            addOnScrollListener(mOnScrollListener);
        }
        isLoadingMore = false;
        mIsLoadMoreWidgetEnabled = true;

    }

    /**
     * 禁用加载更多
     */
    @Override
    public void disableLoadmore() {
        mOnScrollListener = null;
        mIsLoadMoreWidgetEnabled = false;
    }

    @Override
    public void hideLoadMoreView() {
        mIsLoadMoreWidgetEnabled = false;
        mAdapter.setIsLoadMoreIsShow(false);
    }

    public void showLoadMoreView() {
        mIsLoadMoreWidgetEnabled = false;
        mAdapter.setIsLoadMoreIsShow(true);
    }

    /**
     * 完成加载更多
     */
    @Override
    public void completeLoadMore() {
        enableLoadmore();

        mIsLoadMoreWidgetEnabled = true;
        isLoadingMore = false;
        if (mAdapter != null) {
            mAdapter.setIsLoadMoreIsShow(true);
        }
    }

    protected void setDefaultScrollListener() {
        removeOnScrollListener(mOnScrollListener);
        mOnScrollListener = new OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        };

        addOnScrollListener(mOnScrollListener);
    }


}
